package com.naiterui.ehp.bs.wechat.service.impl;

import com.naiterui.ehp.bs.wechat.constants.WeChatConstant;
import com.naiterui.ehp.bs.wechat.protocol.result.MaterialUpResult;
import com.naiterui.ehp.bs.wechat.protocol.result.MediaVideo;
import com.naiterui.ehp.bs.wechat.protocol.result.TempMediaUpResult;
import com.naiterui.ehp.bs.wechat.service.IAccessTokenService;
import com.naiterui.ehp.bs.wechat.service.IMediaApiService;
import com.naiterui.ehp.bs.wechat.utils.WeChatApiUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 微信多媒体素材管理
 *
 * @author zhoupeipei
 * @date 2019-07-03 20:15
 * @since 1.0.0
 */
@Service
public class MediaApiServiceImpl implements IMediaApiService {

    /**
     * 图片素材
     */
    public static final String MEDIA_TYPE_IMAGE = WeChatConstant.MediaFileType.IMAGE;
    /**
     * 语音素材
     */
    public static final String MEDIA_TYPE_VOICE = WeChatConstant.MediaFileType.VOICE;
    /**
     * 视频素材
     */
    public static final String MEDIA_TYPE_VIDEO = WeChatConstant.MediaFileType.VIDEO;
    /**
     * 缩略图素材
     */
    public static final String MEDIA_TYPE_THUMB = WeChatConstant.MediaFileType.THUMB;

    @Autowired
    IAccessTokenService accessTokenService;

    @Override
    public String uploadTempMedia(String type, String filePath) {
        FileSystemResource resource = new FileSystemResource(filePath);
        TempMediaUpResult result = Optional.ofNullable(resource)
                .map(file -> WeChatApiUtil.tempMediaUpload(accessTokenService.accessToken(), file, type))
                .orElse(null);
        return Optional.ofNullable(result).map(TempMediaUpResult::getMediaId).orElse(null);
    }

    @Override
    public byte[] downloadTempMedia(String mediaId) {
        return Optional.ofNullable(mediaId)
                .map(m -> WeChatApiUtil.tempMediaDownload(accessTokenService.accessToken(), mediaId))
                .orElse(new byte[]{});
    }

    @Override
    public String getTempVideoUrl(String mediaId) {
        return Optional.ofNullable(mediaId)
                .map(m -> WeChatApiUtil.tempVideoDownloadUrl(accessTokenService.accessToken(), mediaId))
                .map(MediaVideo::getVideoUrl)
                .orElse("");
    }

    @Override
    public String uploadMedia(String type, String filePath) {
        if (StringUtils.isBlank(filePath)) {
            return "";
        }
        FileSystemResource resource = new FileSystemResource(filePath);
        MaterialUpResult result = Optional.ofNullable(resource)
                .map(file -> WeChatApiUtil.mediaUpload(accessTokenService.accessToken(), file, type))
                .orElse(null);
        return Optional.ofNullable(result).map(MaterialUpResult::getMediaId).orElse(null);
    }
}
